using Tutorial1_Spawner;
using Tutorial2_SinMove;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using Random = Unity.Mathematics.Random;

/*
 *TLS : Thread Local Storage : 子线程访问自己的内容，以免造成竞争
 */

namespace Tutorial3_Jobs
{
    [BurstCompile]
    public partial struct TLS_Job : IJobEntity
    {
        [NativeDisableContainerSafetyRestriction]
        public NativeArray<Random> Randoms;
        
        [NativeSetThreadIndex] // 会被系统自己填充当前ThreadID index
        private int m_ThreadId;
        
        [ReadOnly] public float deltaTime;
        
        private void Execute(ref LocalTransform localTransform, in CubeTag cubeTag)
        {
            var rd = Randoms[m_ThreadId];
            float3 nextFloat3Direction = rd.NextFloat3Direction();
            // 随便写的，效果是有点抖
            localTransform.Position += nextFloat3Direction * 5F * deltaTime;

            rd.state = rd.NextUInt();
            Randoms[m_ThreadId] = rd;
        }
    }
}
